package com.gas.project.system.user.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.gas.project.gas.grade.domain.CourseGrade;
import com.gas.project.gas.grade.domain.CourseValidGrade;
import com.gas.project.gas.grade.service.ICourseGradeService;
import com.gas.project.gas.resit.domain.CourseResit;
import com.gas.project.gas.resit.service.ICourseResitService;
import com.gas.project.gas.student.domain.Student;
import com.gas.project.gas.student.service.IStudentService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gas.common.constant.ShiroConstants;
import com.gas.common.utils.CookieUtils;
import com.gas.common.utils.DateUtils;
import com.gas.common.utils.ServletUtils;
import com.gas.common.utils.StringUtils;
import com.gas.common.utils.text.Convert;
import com.gas.framework.config.GasConfig;
import com.gas.framework.shiro.service.PasswordService;
import com.gas.framework.web.controller.BaseController;
import com.gas.framework.web.domain.AjaxResult;
import com.gas.project.system.config.service.IConfigService;
import com.gas.project.system.menu.domain.Menu;
import com.gas.project.system.menu.service.IMenuService;
import com.gas.project.system.user.domain.User;

/**
 * 首页 业务处理
 *
 * @author xyl
 */
@Controller
public class IndexController extends BaseController {
    @Autowired
    private IMenuService menuService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private GasConfig gasConfig;


    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap) {
        // 取身份信息
        User user = getSysUser();
        // 根据用户id取出菜单
        List<Menu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        mmap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        mmap.put("copyrightYear", gasConfig.getCopyrightYear());
        mmap.put("demoEnabled", gasConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName())) {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap) {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password) {
        User user = getSysUser();
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("服务器超时，请重新登陆");
        }
        if (passwordService.matches(user, password)) {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin() {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response) {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    @Autowired
    private IStudentService studentService;
    @Autowired
    private ICourseResitService courseResitService;
    @Autowired
    private ICourseGradeService courseGradeService;

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap) {
        User sysUser = getSysUser();
        if (sysUser.isStudent()) {
            String content = "", grade = "";
            Student student = studentService.selectStudentById(sysUser.getLoginName());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            long start = student.getAdmissionsTime().getTime();
            long end = System.currentTimeMillis();
            long day = (end - start) / 24 / 60 / 60 / 1000;
            switch ((int) (day / 180 + 1)) {
                case 1:
                    grade = "大一上学期";
                    break;
                case 2:
                    grade = "大一下学期";
                    break;
                case 3:
                    grade = "大二上学期";
                    break;
                case 4:
                    grade = "大二下学期";
                    break;
                case 5:
                    grade = "大三上学期";
                    break;
                case 6:
                    grade = "大三下学期";
                    break;
                case 7:
                    grade = "大四上学期";
                    break;
                default:
                    grade = "大四下学期";
                    break;
            }
            //获取有效成绩数据
            CourseValidGrade cvg = new CourseValidGrade();
            cvg.setStudentNumber(sysUser.getLoginName());

            CourseGrade courseGrade = new CourseGrade();
            courseGrade.setStudentNumber(sysUser.getLoginName());
            courseGrade.setCoueseNature("重修");

            CourseResit courseResit = new CourseResit();
            courseResit.setStudentNumber(sysUser.getLoginName());

            if(StringUtils.equals(student.getStudentType(),"本科")){
                if ("大四下学期".equals(grade)) {
                    CourseValidGrade courseValidGrade = courseGradeService.selectValidGradeCollect(cvg);
                    if(ObjectUtils.isNotEmpty(courseValidGrade)){
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点4分" +
                                "，总实修平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint()
                                +"，毕业状态：" + student.getGraduationStatus();
                    }else{
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点4分" +
                                "，总实修平均学分绩点：" + 0
                                +"，毕业状态：" + student.getGraduationStatus();
                    }
                } else {
                    cvg.setStartYear(2021);
                    cvg.setSemester("下");
                    List<CourseValidGrade> courseValidGrades = courseGradeService.selectValidGradeList(cvg);
                    if(courseValidGrades.size() > 0){
                        CourseValidGrade courseValidGrade = courseValidGrades.get(0);
                        content = student.getStudentType() + "：" +sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点4分" +
                                "，本学期平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint();
                    }else{
                        content = student.getStudentType() + "：" +sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点4分" +
                                "，本学期平均学分绩点：" + 0;
                    }
                }
            }else{
                if ("大二下学期".equals(grade)) {
                    CourseValidGrade courseValidGrade = courseGradeService.selectValidGradeCollect(cvg);
                    if(ObjectUtils.isNotEmpty(courseValidGrade)){
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点2分" +
                                "，总平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint()
                                +"，毕业状态：" + student.getGraduationStatus();
                    }else{
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点4分" +
                                "，总实修平均学分绩点：" + 0
                                +"，毕业状态：" + student.getGraduationStatus();
                    }
                } else {
                    cvg.setStartYear(2021);
                    cvg.setSemester("下");
                    List<CourseValidGrade> courseValidGrades = courseGradeService.selectValidGradeList(cvg);
                    if(courseValidGrades.size() > 0){
                        CourseValidGrade courseValidGrade = courseValidGrades.get(0);
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点2分" +
                                "，本学期平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint();
                    }else{
                        content = student.getStudentType() + "：" +sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点4分" +
                                "，本学期平均学分绩点：" + 0;
                    }
                }
            }
            mmap.put("content", content);
            mmap.put("gaa", "1");
        }
        return "main";
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate) {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate) {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0) {
            if (StringUtils.isNull(pwdUpdateDate)) {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
